#include "lx_ext.h"
#include "bsp_w25qxx.h"
#include "osal.h"
#include "slog.h"





static ULONG sector_buffer[FLASH_WORDS_PER_SECTOR];

static UINT lx_nor_flash_driver_read(ULONG *flash_address, ULONG *destination, ULONG words)
{
    W25QXX_Read((uint8_t *)destination, (uint32_t)flash_address, (uint16_t)(words*4));
    return (LX_SUCCESS);
}

static UINT lx_nor_flash_driver_write(ULONG *flash_address, ULONG *source, ULONG words)
{
    W25QXX_Write_NoCheck((uint8_t *)source, (uint32_t)flash_address, (uint16_t)(words*4));
    return (LX_SUCCESS);
}

static UINT lx_nor_flash_driver_block_erase(ULONG block, ULONG erase_count)
{
    LX_PARAMETER_NOT_USED(erase_count);

    W25QXX_EraseSector(block * FLASH_SIZE_BYTE_PER_SECTOR);
    return (LX_SUCCESS);
}

/* 用于校验指定的块是否擦除成功 */
static UINT lx_nor_flash_driver_block_erased_verify(ULONG block)
{
    LX_PARAMETER_NOT_USED(block);
    
    return (LX_SUCCESS);
}

/* 用于检测系统错误，依赖于驱动程序 */
static UINT lx_nor_flash_driver_system_error(UINT error_code)
{
    LX_PARAMETER_NOT_USED(error_code);
    
    return (LX_ERROR);
}   

static UINT nor_driver_initialize(LX_NOR_FLASH *nf)
{
    /* Setup the base address of the flash memory.  */
    nf->lx_nor_flash_base_address = (ULONG *)FLASH_BASE_ADDR;

  /* Setup geometry of the flash.  */
	nf->lx_nor_flash_total_blocks = FLASH_TOTAL_BLOCKS;
    nf->lx_nor_flash_words_per_block = FLASH_WORDS_PER_SECTOR;

//    nf->lx_nor_flash_total_physical_sectors      = FLASH_TOTAL_BLOCKS;
//    nf->lx_nor_flash_physical_sectors_per_block  = 1;


    /* Setup  driver’s initialization function */
    nf->lx_nor_flash_driver_read                = lx_nor_flash_driver_read;
    nf->lx_nor_flash_driver_write               = lx_nor_flash_driver_write;
    nf->lx_nor_flash_driver_block_erase         = lx_nor_flash_driver_block_erase;
    nf->lx_nor_flash_driver_block_erased_verify = lx_nor_flash_driver_block_erased_verify;
    nf->lx_nor_flash_driver_system_error        = lx_nor_flash_driver_system_error;

    /* Setup local buffer for NOR flash operation. This buffer must be the sector size of the NOR flash memory.  */
    nf->lx_nor_flash_sector_buffer = sector_buffer;

    return(LX_SUCCESS);
}

LX_NOR_FLASH XM25Q128A;

unsigned int LX_NOR_FLASH_Init(void)
{
    UINT ret;

    ret = _lx_nor_flash_initialize();

    ret = _lx_nor_flash_open(&XM25Q128A, FLASH_NAME, nor_driver_initialize);
    return ret;
}

void LX_NOR_FLASH_Test(void)
{
    uint8_t wbuf[512] = "http://www.optomedic.com";
    uint8_t rbuf[512] = {0};
    
    _lx_nor_flash_sector_write(&XM25Q128A, 1, wbuf);
    
    _lx_nor_flash_sector_read(&XM25Q128A, 1, rbuf);

    printf("lx read %s\r\n", rbuf);
}









